import { HttpClient } from 'tsrpc-browser';
import { ElNotification } from 'element-plus'
import { HandDrawnNotification } from '@/tool/handDrawnToast'
import router from '@/router';
import { serviceProto, ServiceType } from '@/shared/poto/serviceProto';

// 动态获取API服务器地址
const getApiServer = () => {
  // 如果环境变量存在，使用环境变量
  if (process.env.VUE_APP_API_BASE) {
    return process.env.VUE_APP_API_BASE;
  }

  // 否则根据当前页面地址动态构建API地址
  const protocol = window.location.protocol;
  const hostname = window.location.hostname;
  const port = '3001'; // 假设后端服务器在3001端口，如果不是请修改

  return `${protocol}//${hostname}:${port}`;
};

// 创建全局唯一的 apiClient，需要时从该文件引入
const apiClient = new HttpClient(serviceProto, {
  server: getApiServer(),
  json: true,
});

export const callApi = async <T extends string & keyof ServiceType['api']>(apiName: T, req: ServiceType['api'][T]['req']) => {
  // 这里可以添加调用 API 的逻辑
  const _token = localStorage.getItem('token') || undefined;
  if (_token) {
    req._token = _token;
  }
  const res = await apiClient.callApi(apiName, req)
  if (res.isSucc) {
    return res.res
  } else {
    switch (res.err.type) {
      case 'ApiError':
        HandDrawnNotification.error({
          title: '出错啦',
          message: res.err.message,
        })
        break;
      case 'NetworkError':
        HandDrawnNotification.error({
          title: '网络错误',
          message: res.err.message,
        })
        break;
      case 'ServerError':
        HandDrawnNotification.error({
          title: '系统出错',
          message: res.err.message,
        })
        router.push('/')
        break;
      case 'ClientError':
        HandDrawnNotification.error({
          title: '操作错误',
          message: res.err.message,
        })
        break;
      default:
        HandDrawnNotification.error({
          title: '未知错误',
          message: res.err.message,
        })
        break;
    }
  }
  return undefined;
}
